/*
 * thread.h
 * 
 * Copyright 2012 Laura <arual13@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 */

#ifndef THREAD_LIB
#define THREAD_LIB

#include <setjmp.h>
#include "config.h"


/* Wait time to make it easier to read the output of the methods */
#define SECOND 1000000
#define STACK_SIZE 40096

#ifdef __x86_64__
// code for 64 bit Intel arch

typedef unsigned long address_t;
#define JB_StackPointer 6
#define JB_ProgramCounter 7

#else
// code for 32 bit Intel arch

typedef unsigned int address_t;
#define JB_StackPointer 4
#define JB_ProgramCounter 5

#endif

/* Struct for the thread and definition of type threadNode*/
typedef struct threadNode 
{
    long int id;
    long int* tickets;
    long int tickets_num;
    long int work_units; /* 1 work unit = 50 terms of the Taylor series */
    long int work_left;
    long double quantum;
    sigjmp_buf env;
    char* stack;
    long double current_result;
    struct threadNode* next;
} threadNode;

typedef struct
{
    threadNode* head;
    threadNode* tail;
    
} threadQueue;

configuration *config;
threadNode *currentThread;

long int units_to_complete;
long double pi_result;
sigjmp_buf handler;
//fabio -> flag to know if the handler is active or not
int handler_active;
//end
void continue_handler();
int pause_handler();
void start_thread(threadNode *threadInstance);
int pause_thread(threadNode *threadInstance);
void switchThreads();
void operation(void);
void count_operation(void);
threadQueue* initializeThreads(configuration *config);
void switch_Threads(int thread_id);
void setup_threads();
threadQueue* addElement (threadQueue* list, threadNode* node);
threadQueue* removeElement (threadQueue* list, threadNode* nodeToDelete);
threadQueue* newQueue(long int threads_num );
void printQueue(threadQueue* list);
void printNode(threadNode* node);
threadNode *newNode(long int id, long int work_units, long int tickets_num, long int* tickets, long double quantum);
void freeQueue(threadQueue *list);
void freeNode(threadNode *node);
void moveElement (threadQueue* listSource, threadQueue* destination, threadNode* node);

#endif
